from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep
import csv


wd = webdriver.Chrome(service=Service(r'D:\soft\selenium\chromedriver.exe'))
wd.get('http://**************.com')
mainWindow = wd.current_window_handle
sleep(1)
selectPosition=wd.find_element(By.CSS_SELECTOR,'#work_position_input')
selectPosition.click()
sleep(1)
oldPositon=wd.find_element(By.CSS_SELECTOR,'#work_position_click_multiple_selected_each_150000')
oldPositon.click()
sleep(1)
addPosition=wd.find_element(By.CSS_SELECTOR,'#work_position_click_center_right_list_category_000000_020000')
addPosition.click()
# sleep(1)
comfermButton=wd.find_element(By.CSS_SELECTOR,'#work_position_click_bottom_save')
comfermButton.click()
search=wd.find_element(By.CSS_SELECTOR,'p.ipt #kwdselectid')
search.send_keys('python\n')
sleep(1)

number=0
listAllJob=[]
while True:
    number+=1
    print(number)
    if number==10:
        break
    resultlist=wd.find_elements(By.CSS_SELECTOR,'#resultList [class="el"]')
    for e in resultlist:
        jobTitle=e.find_element(By.CSS_SELECTOR,'.t1 a')
        companyName = e.find_element(By.CSS_SELECTOR,'.t2 a')
        place = e.find_element(By.CSS_SELECTOR,'#resultList [class="el"] .t3')
        salary = e.find_element(By.CSS_SELECTOR,'#resultList [class="el"] .t4')
        date = e.find_element(By.CSS_SELECTOR,'#resultList [class="el"] .t5')
        listOneJob=[jobTitle.text,companyName.text,place.text,salary.text,date.text]
        name=jobTitle.text
        jobTitle.click()
        sleep(2)
        try:
            for handle in wd.window_handles:
                # 先切换到该窗口
                wd.switch_to.window(handle)
                # 得到该窗口的标题栏字符串，判断是不是我们要操作的那个窗口
                if name in wd.title:
                    # 如果是，那么这时候WebDriver对象就是对应的该该窗口，正好，跳出循环，
                    break
            sleep(2)
            description=''
            content=wd.find_elements(By.CSS_SELECTOR,'.tBorderTop_box [class="bmsg job_msg inbox"] p')
            for p in content:
                description+=p.text
            listOneJob.append(description)
            listAllJob.append(listOneJob)
            wd.close()
            sleep(1)
            wd.switch_to.window(mainWindow)
            sleep(2)
        except:
            wd.close()
            sleep(1)
            wd.switch_to.window(mainWindow)
            sleep(2)
            continue
    nextPage=wd.find_element(By.CSS_SELECTOR,'.dw_page ul li:nth-last-child(1)')
    nextPage.click()
    sleep(2)

with open("1.csv", "w", newline='',encoding='utf-8-sig') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["岗位","公司","地点",'工资','发布日期','职位介绍'])
    writer.writerows(listAllJob)
print('Done--------------------')


